<template>
  <div>
    <el-breadcrumb separator="/" style="margin-bottom: 20px" v-if="showBind">
      <el-breadcrumb-item>
        <a @click="showBind = false">收款平台</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <a>收款账号</a>
      </el-breadcrumb-item>
    </el-breadcrumb>

    <div v-if="!showBind">
      <el-form ref="queryFormRef" :model="payAppQueryParams" :inline="true">
        <el-form-item label="应用ID" prop="appId">
          <el-input v-model="payAppQueryParams.appId" placeholder="请输入应用ID" clearable @keyup.enter="getPayAppList" />
        </el-form-item>
        <el-form-item label="支付平台" prop="typeId">
          <el-select v-model="payAppQueryParams.typeId" clearable placeholder="请输入支付平台">
            <el-option v-for="item in payList" :value="item.typeId" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否循环收单" prop="isLoop">
          <el-select v-model="payAppQueryParams.isLoop" placeholder="请选择是是否循环收单" @change="getPayAppList" clearable>
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收单几次进入循环" prop="nextCount">
          <el-input v-model="payAppQueryParams.nextCount" placeholder="请输入收单几次进入循环" clearable @keyup.enter="getPayAppList" />
        </el-form-item>
        <el-form-item label="是否检查账号" prop="isCheck">
          <el-select v-model="payAppQueryParams.isCheck" placeholder="请选择是否检查账号" @change="getPayAppList" clearable>
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getPayAppList">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" icon="plus" @click="addPayApp">添加收款平台</el-button>
      <el-table v-loading="loading" :data="PayAppList" class="mt-[20px]">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" v-if="true" />
        <el-table-column label="应用ID" align="center" prop="appId" />
        <el-table-column label="支付平台" align="center" prop="typeId">
          <template #default="{ row }">
            <div>{{ payList.filter((item) => item.typeId == row.typeId)[0]?.name || row.payTypeId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="是否循环收单" align="center" prop="isLoop" />
        <el-table-column label="收单几次进入循环" align="center" prop="nextCount" />
        <el-table-column label="是否检查账号" align="center" prop="isCheck" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="flex flex-wrap justify-center gap-x-2">
              <el-tooltip content="查看账号" placement="top">
                <el-button link type="primary" icon="view" @click="openBind" v-hasPermi="['system:PayAppTypes:edit']">查看收款账户</el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button style="margin: 0" link type="primary" icon="Edit" @click="editPayApp(scope.row)" v-hasPermi="['system:PayAppTypes:edit']"
                  >编辑</el-button
                >
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  style="margin: 0"
                  link
                  type="danger"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:PayAppTypes:remove']"
                  >删除</el-button
                >
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div v-if="showBind">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="账号名称" prop="accountName">
          <el-input v-model="queryParams.accountName" placeholder="请输入账号名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="支付平台ID" prop="payTypeId">
          <el-input v-model="queryParams.payTypeId" placeholder="请输入支付平台ID" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="域名" prop="domain">
          <el-input v-model="queryParams.domain" placeholder="请输入域名" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="ip" prop="ip">
          <el-input v-model="queryParams.ip" placeholder="请输入ip" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button icon="RefreshLeft" @click="showBind = false">返回</el-button>
      <el-button type="primary" icon="Pointer" @click="addBindAccout">绑定账号</el-button>
      <el-table v-loading="accountLoading" :data="PayAccountList" @selection-change="handleSelectionChange" class="mt-[20px]">
        <el-table-column label="代理名称" align="center" prop="agentName" />
        <el-table-column label="账号ID" align="center" prop="accountId" v-if="false" />
        <el-table-column label="账号名称" align="center" prop="accountName" />
        <el-table-column label="支付平台" align="center" prop="payTypeId">
          <template #default="{ row }">
            <div>{{ payList.filter((item) => item.typeId == row.payTypeId)[0]?.name || row.payTypeId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="域名" align="center" prop="domain" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="API类型" align="center" prop="apiType">

          </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="danger" icon="Delete" @click="handleAdd(scope.row)" v-hasPermi="['system:PayAccount:edit']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="accountTotal > 0"
        :total="accountTotal"
        v-model:page="accountQueryParams.pageNum"
        v-model:limit="accountQueryParams.pageSize"
        @pagination="getAccountList"
      />
    </div>

    <!-- 绑定账号弹窗 -->
    <el-dialog v-model="bindDialog.show" title="绑定收款账号" width="1200px">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="账号名称" prop="accountName">
          <el-input v-model="queryParams.accountName" placeholder="请输入账号名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="支付平台ID" prop="payTypeId">
          <el-input v-model="queryParams.payTypeId" placeholder="请输入支付平台ID" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="域名" prop="domain">
          <el-input v-model="queryParams.domain" placeholder="请输入域名" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="ip" prop="ip">
          <el-input v-model="queryParams.ip" placeholder="请输入ip" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="accountLoading" :data="PayAccountList" @selection-change="handleSelectionChange" class="mt-[20px]">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="代理名称" align="center" prop="agentName" />
        <el-table-column label="账号ID" align="center" prop="accountId" v-if="false" />
        <el-table-column label="账号名称" align="center" prop="accountName" />
        <el-table-column label="支付平台" align="center" prop="payTypeId">
          <template #default="{ row }">
            <div>{{ payList.filter((item) => item.typeId == row.payTypeId)[0]?.name || row.payTypeId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="域名" align="center" prop="domain" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="API类型" align="center" prop="apiType" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleAdd(scope.row)" v-hasPermi="['system:PayAccount:edit']">绑定</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="accountTotal > 0"
        :total="accountTotal"
        v-model:page="accountQueryParams.pageNum"
        v-model:limit="accountQueryParams.pageSize"
        @pagination="getAccountList"
      />
    </el-dialog>

    <!-- 添加或修改收款平台 -->
    <el-dialog :title="payAppDialog.title" v-model="payAppDialog.show" width="500px" append-to-body>
      <el-form ref="PayAppTypesFormRef" :model="payAppForm" :rules="payAppRules">
        <el-form-item label="支付平台" prop="typeId">
          <el-select v-model="payAppForm.typeId" clearable placeholder="请输入支付平台">
            <el-option v-for="item in payList" :value="item.typeId" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否循环收单" prop="isLoop">
          <el-switch v-model="payAppForm.isLoop" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item v-if="payAppForm.isLoop" label="收单几次进入循环" prop="nextCount">
          <el-input-number v-model="payAppForm.nextCount" placeholder="请输入收单几次进入循环" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitPayAppForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改应用收款账号对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <el-form ref="PayAppAccountFormRef" :model="form" :rules="rules">
        <div class="grid grid-cols-3">
          <el-form-item label="总额度" prop="totalLimit">
            <el-input-number v-model="form.totalLimit" placeholder="总额度" />
          </el-form-item>
          <el-form-item label="最小订单金额" prop="minMoney">
            <el-input-number v-model="form.minMoney" placeholder="最小订单金额" />
          </el-form-item>
          <el-form-item label="最大订单金额" prop="maxMoney">
            <el-input-number v-model="form.maxMoney" placeholder="最大订单金额" />
          </el-form-item>
          <el-form-item label="收款总金额" prop="totalMoney">
            <el-input-number v-model="form.totalMoney" placeholder="收款总金额" />
          </el-form-item>
          <el-form-item label="额度增长率" prop="increaseRate">
            <el-input-number v-model="form.increaseRate" placeholder="额度增长率" />
          </el-form-item>
          <el-form-item label="失败次数限制" prop="failLimit">
            <el-input-number v-model="form.failLimit" placeholder="失败次数限制" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="form.sort" placeholder="排序" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch v-model="form.status" active-value="1" inactive-value="0" />
          </el-form-item>
        </div>

        <div class="grid grid-cols-2 gap-[40px]">
          <el-form-item label="额度刷新时间" prop="refreshTime">
            <el-time-select v-model="form.refreshTime" style="width: 100%" start="00:00" step="00:30" end="23:59" placeholder="请选择额度刷新时间" />
          </el-form-item>
          <el-form-item label="支付方式" prop="payMethod">
            <el-select v-model="form.payMethod" clearable placeholder="请选择支付方式">
              <el-option v-for="item in payMethods" :value="item.value" :label="item.label"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <el-form-item label="收款方式" prop="receiveList">
          <el-input v-model="form.receiveList" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <div>
          <div class="flex justify-between">
            <span>收款方式</span>
            <el-button size="small" icon="Plus" type="primary" @click="showPayReceive = true">添加</el-button>
          </div>
          <el-table v-loading="loading" :data="PayReceiveList" style="margin-top: 10px">
            <el-table-column label="支付名称" align="center" show-overflow-tooltip prop="name" />
            <el-table-column label="币种" align="center" prop="currencies" show-overflow-tooltip />
            <el-table-column label="商户国家" align="center" prop="country" show-overflow-tooltip />
            <el-table-column label="支付代码" align="center" prop="code" show-overflow-tooltip />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:PayReceive:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 收款方式弹窗 -->
  <el-dialog v-model="showPayReceive" append-to-body title="选择账号">
    <el-table v-loading="loading" :data="PayReceiveList" style="margin-top: 10px" @selection-change="handleSelectionReceiveChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="支付名称" align="center" show-overflow-tooltip prop="name" />
      <el-table-column label="币种" align="center" prop="currencies" show-overflow-tooltip />
      <el-table-column label="商户国家" align="center" prop="country" show-overflow-tooltip />
      <el-table-column label="支付代码" align="center" prop="code" show-overflow-tooltip />
    </el-table>
    <div class="flex justify-end mt-[10px]">
      <el-button type="primary" @click="submitReceive">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup name="PayAppAccount" lang="ts">
import { listPayAccount } from '@/api/pay/PayAccount';
import { listPayAppAccount, getPayAppAccount, delPayAppAccount, addPayAppAccount, updatePayAppAccount } from '@/api/pay/PayAppAccount';
import { PayAppAccountVO, PayAppAccountQuery, PayAppAccountForm } from '@/api/pay/PayAppAccount/types';
import { listPayAppTypes, getPayAppTypes, delPayAppTypes, addPayAppTypes, updatePayAppTypes } from '@/api/pay/PayAppTypes';
import { selecTypetList } from '@/api/pay/PayType/index';
import { listPayReceive, getPayReceive, delPayReceive, addPayReceive, updatePayReceive } from '@/api/pay/PayReceive';
import { PayReceiveVO, PayReceiveQuery, PayReceiveForm } from '@/api/pay/PayReceive/types';
const props = defineProps({
  dataInfo: {
    type: Object,
    default: () => {}
  }
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const PayAppAccountList = ref<PayAppAccountVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const PayAppAccountFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PayAppAccountForm = {
  status: undefined,
  totalLimit: undefined,
  increaseRate: undefined,
  refreshTime: undefined,
  minMoney: undefined,
  maxMoney: undefined,
  totalMoney: undefined,
  payMethod: undefined,
  receiveList: undefined,
  failLimit: undefined,
  sort: undefined
};
const data = reactive<PageData<PayAppAccountForm, PayAppAccountQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appId: undefined,
    payTypeId: undefined,
    accountId: undefined,
    status: undefined,
    totalLimit: undefined,
    increaseRate: undefined,
    refreshTime: undefined,
    minMoney: undefined,
    maxMoney: undefined,
    totalMoney: undefined,
    payMethod: undefined,
    receiveList: undefined,
    failLimit: undefined,
    sort: undefined,
    clientId: undefined,
    agentId: undefined,
    params: {}
  },
  rules: {
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    totalLimit: [{ required: true, message: '总额度不能为空', trigger: 'blur' }],
    increaseRate: [{ required: true, message: '额度增长率不能为空', trigger: 'blur' }],
    refreshTime: [{ required: true, message: '额度刷新时间不能为空', trigger: 'blur' }],
    minMoney: [{ required: true, message: '最小订单金额不能为空', trigger: 'blur' }],
    maxMoney: [{ required: true, message: '最大订单金额不能为空', trigger: 'blur' }],
    totalMoney: [{ required: true, message: '收款总金额不能为空', trigger: 'blur' }],
    payMethod: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
    receiveList: [{ required: true, message: '收款方式不能为空', trigger: 'blur' }],
    failLimit: [{ required: true, message: '失败次数限制不能为空', trigger: 'blur' }],
    sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询应用收款账号列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPayAppAccount(queryParams.value);
  PayAppAccountList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  payAppDialog.show = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  PayAppAccountFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PayAppAccountVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const accountInfo = ref({});
const handleAdd = (row) => {
  reset();
  accountInfo.value = row;
  dialog.visible = true;
  dialog.title = '设置应用收款账号';
  let config = JSON.parse(payList.value.find((item) => item.typeId == row.payTypeId)?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, ''));
  payMethods.value = config.apiConfig;
  getPayReceiveList();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PayAppAccountVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getPayAppAccount(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改应用收款账号';
};

/** 提交按钮 */
const submitForm = () => {
  PayAppAccountFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.appId = props.dataInfo.appId;
      form.value.accountId = accountInfo.value.accountId;
      buttonLoading.value = true;
      if (form.value.id) {
        await updatePayAppAccount(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPayAppAccount(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      showBind.value = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PayAppAccountVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除应用收款账号编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delPayAppAccount(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/PayGroupAccount/export',
    {
      ...queryParams.value
    },
    `PayAppAccount_${new Date().getTime()}.xlsx`
  );
};

// 配置收款账户
const payTypeShow = ref('');
const payList = ref([]);
const getPayList = async () => {
  let res = await selecTypetList();
  payList.value = res.data;
  payTypeShow.value = payList.value[0].name;
};
//支付方式
const payMethods = ref([]);
// 绑定账号
const showBind = ref(false);
const openBind = () => {
  showBind.value = true;
  getAccountList();
};
const accountTotal = ref(0);
const accountQueryParams = reactive({
  pageSize: 10,
  pageNum: 1
});
const accountLoading = ref(false);
const PayAccountList = ref([]);
const getAccountList = async () => {
  accountLoading.value = true;
  let res = await listPayAccount();
  PayAccountList.value = res.rows;
  accountLoading.value = false;
};

// 支付平台列表
const payAppQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  appId: undefined,
  typeId: undefined,
  isLoop: undefined,
  nextCount: undefined,
  isCheck: undefined,
  params: {}
});
const PayAppList = ref([]);
const payAppDialog = reactive({
  show: false,
  title: ''
});
const addPayApp = () => {
  payAppDialog.show = true;
  payAppDialog.title = '新增收款平台';
  payAppForm.value = {
    appId: '',
    typeId: '',
    isLoop: '',
    nextCount: 0,
    isCheck: ''
  };
};
const editPayApp = (row) => {
  payAppDialog.show = true;
  payAppDialog.title = '编辑收款平台';
  payAppForm.value = row;
};
const payAppForm = ref({
  appId: '',
  typeId: '',
  isLoop: '',
  nextCount: 0,
  isCheck: ''
});
const payAppRules = ref({
  typeId: [{ required: true, message: '支付平台不能为空', trigger: 'change' }],
  nextCount: [{ required: true, message: '循环数量不能为空', trigger: 'change' }]
});
const getPayAppList = async () => {
  let res = await listPayAppTypes(payAppQueryParams.value);
  PayAppList.value = res.rows;
};
const PayAppTypesFormRef = ref(null);
const submitPayAppForm = () => {
  PayAppTypesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let res;
      payAppForm.value.appId = props.dataInfo.appId;
      if (payAppDialog.title == '新增收款平台') {
        res = await addPayAppTypes(payAppForm.value).finally(() => (buttonLoading.value = false));
      } else {
        res = await updatePayAppTypes(payAppForm.value).finally(() => (buttonLoading.value = false));
      }
      payAppDialog.show = false;
      getPayAppList();
      PayAppTypesFormRef.value.resetFields();
    }
  });
};

//绑定账号弹窗
const bindDialog = reactive({
  show: false
});
const addBindAccout = () => {
  bindDialog.show = true;
};

// 收款方式
const PayReceiveList = ref<PayReceiveVO[]>([]);
const getPayReceiveList = async () => {
  loading.value = true;
  const res = await listPayReceive(queryParams.value);
  PayReceiveList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
const showPayReceive = ref(false);
const selectReceiveList = ref([]);
const handleSelectionReceiveChange = (val) => {
  selectReceiveList.value = val;
};
const submitReceive = () => {
  console.log(selectReceiveList.value);
};

onMounted(() => {
  getList();
  getPayList();
  getPayAppList();
});
</script>

<style lang="scss" scoped>
:deep(.el-input-number) {
  width: 90%;
}
</style>
